//
//  GYCartVC_V2.m
//  GYDemo
//
//  Created by mac on 2018/6/27.
//  Copyright © 2018年 mac. All rights reserved.
//

//
//                .-~~~~~~~~~-._       _.-~~~~~~~~~-.
//            __.'              ~.   .~              `.__
//          .'//                  \./                  \\`.
//        .'//                     |                     \\`.
//      .'// .-~"""""""~~~~-._     |     _,-~~~~"""""""~-. \\`.
//    .'//.-"                 `-.  |  .-'                 "-.\\`.
//  .'//______.============-..   \ | /   ..-============.______\\`.
//.'______________________________\|/______________________________`.
//
//

#import "GYCartVC.h"
#import "Head.h"

@interface GYCartVC ()
@property (nonatomic,strong) GYCartViewModel *viewModel;
@property (nonatomic,strong) UIView *confirmV;
@property (nonatomic,strong) UIButton *allSignIV;
@property (nonatomic,strong) UILabel *finalPriceLB;
@property (nonatomic,strong) UIButton *confirmBtn;
@end

@implementation GYCartVC
#pragma mark - getter and setter
-(GYCartViewModel *)viewModel
{
    if (!_viewModel) {
        _viewModel = [GYCartViewModel shareInterface];
    }
    return _viewModel;
}
-(UIButton *)allSignIV
{
    if (!_allSignIV) {
        _allSignIV = [UIButton new];
        _allSignIV.frame = WFCGRectMake(0, 0, 18, 18);
        _allSignIV.centerX = WFCGFloatX(21);
        _allSignIV.centerY = WFCGFloatY(20) + 5;
        @WeakSelf;
        [_allSignIV setEnlargeEdge:WFCGFloatY(20)];
        [_allSignIV addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
            [selfp.viewModel chooseAll];
        }];
    }
    return _allSignIV;
}
-(UIView *)confirmV
{
    if (!_confirmV) {
        _confirmV = [UIView new];
        _confirmV.width = self.view.width;
        _confirmV.height = WFCGFloatY(50);
        _confirmV.y = self.view.height;
        _confirmV.backgroundColor = Main_Color_White;
        
        UILabel *alltitle = [UILabel new];
        alltitle.frame = WFCGRectMake(38, 0, 60, 50);
        alltitle.textColor = Main_Color_LightGray;
        alltitle.font = SYSTEMFONT(13);
        alltitle.text = @"全选";
        [_confirmV addSubview:alltitle];
        
        [_confirmV addSubview:self.allSignIV];
        [_confirmV addSubview:self.finalPriceLB];
        [_confirmV addSubview:self.confirmBtn];
    }
    return _confirmV;
}
-(UILabel *)finalPriceLB
{
    if (!_finalPriceLB) {
        _finalPriceLB = [UILabel new];
        _finalPriceLB.frame = WFCGRectMake(375 - 115 - 200, 0, 200, 50);
        _finalPriceLB.font = SYSTEMBOLDFONT(15);
        _finalPriceLB.textAlignment = NSTextAlignmentRight;
        _finalPriceLB.textColor = HEXCOLOR(@"#FC1B36");
    }
    return _finalPriceLB;
}
-(UIButton *)confirmBtn
{
    if (!_confirmBtn) {
        _confirmBtn = [UIButton new];
        _confirmBtn.height = self.confirmV.height;
        _confirmBtn.width = WFCGFloatX(105);
        _confirmBtn.x = _confirmV.width - _confirmBtn.width;
        [_confirmBtn setBackgroundColor:Main_Color_Red forState:UIControlStateNormal];
        _confirmBtn.titleLabel.font = SYSTEMFONT(15);
        [_confirmBtn setTitle:@"去结算" forState:UIControlStateNormal];
        [_confirmBtn setTitleColor:Main_Color_White forState:UIControlStateNormal];
        [_confirmBtn addTarget:self action:@selector(confirmBtnTap:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _confirmBtn;
}
#pragma mark - event
-(void)confirmBtnTap:(id)sender
{
    if (![[GYLoginViewModel shareInterface] loginstatus]) {
        [[GCPresenter shareInterface] loadLogin];
        return;
    }
    NSMutableArray* myArr=[NSMutableArray new];
    for (GYCartShopModel* model in self.viewModel.datas) {
        if (model.is_selected) {
            [myArr addObject:model];
        }
    }
    if (myArr.count==0) {
        [FTIndicator showInfoWithMessage:@"请选择商品"];
        return;
    }
    GYCartConfirmVC *confirm = [GYCartConfirmVC new];
    confirm.viewModel.carViewModel = self.viewModel;
    confirm.passArr=myArr;
    [self.navigationController pushViewController:confirm animated:YES];
}
-(void)noDataBtnTap:(id)sender
{
    GYMainTab *tab = [GCPresenter shareInterface].mainVC;
    tab.selectedIndex = 0;
}
#pragma mark - method
-(void)initilization
{
    self.navigationItem.title = @"购物车";
    self.extendedLayoutIncludesOpaqueBars = YES;
    
    if (@available(iOS 11.0, *)) {
        self.baseTable.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.navigationController.navigationBar.shadowImage = [[UIImage new]rt_darkenWithLevel:0.3f];
    [self setNavgationTheme:0];
    self.isGroup = YES;
    [self.view addSubview:self.baseTable];
    [self.baseTable setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    [self.baseTable setSeparatorColor: Main_Color_BG];
    [self.baseTable setBackgroundColor:Main_Color_BG];
    [self.baseTable setTintColor:Main_Color_BG];
    UIImage *img = [UIImage imageNamed:@"cartNoData"];
    [self.baseTable.noDataBtn setBackgroundImage:img forState:UIControlStateNormal];
    self.baseTable.noDataBtn.width = img.size.width;
    self.baseTable.noDataBtn.height = img.size.height;
    [self.baseTable.noDataBtn setTitle:@"" forState:UIControlStateNormal];
    [WFFunctions WFUIaddbordertoView:self.baseTable.noDataBtn radius:0 width:0.5 color:Main_Color_BG];
    [self.baseTable.noDataBtn addTarget:self action:@selector(noDataBtnTap:) forControlEvents:UIControlEventTouchUpInside];
    @WeakSelf;
    self.baseTable.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [selfp reloadData];
    }];
    [self.view addSubview:self.confirmV];
    [self viewModelBand];
    [self reloadData];
}
-(void)viewModelBand
{
    @WeakSelf;
    GCBaseObservationModel *observation = [GCBaseObservationModel new];
    observation.observation = self.viewModel;
    observation.keyPath = @"datas";
    observation.handler = ^(NSString *keyPath) {
        [selfp reloadView];
    };
    [self registObservation:observation];
}
-(void)reloadView
{
    [self dissmissFTIndicatorProgress];
    [self.baseTable reloadData];
    
    NSString *finalprices = [self.viewModel finalPrice];
    NSMutableAttributedString *mastr = [[NSMutableAttributedString alloc]initWithString:finalprices];
    [mastr addAttribute:NSFontAttributeName value:SYSTEMFONT(12) range:[finalprices rangeOfString:@"合计："]];
    [mastr addAttribute:NSForegroundColorAttributeName value:Main_Color_Gray range:[finalprices rangeOfString:@"合计："]];
    [mastr addAttribute:NSFontAttributeName value:SYSTEMFONT(12) range:NSMakeRange([finalprices rangeOfString:@"."].location, finalprices.length - [finalprices rangeOfString:@"."].location)];
    _finalPriceLB.attributedText = mastr;
    
    UIImage *img = [UIImage imageNamed:self.viewModel.is_selected ? @"Selected" : @"Unselected"];
    [_allSignIV setBackgroundImage:img forState:UIControlStateNormal];
    
    NSString *count = [NSString stringWithFormat:@"%ld",self.viewModel.datas.count];
    [[GCPresenter shareInterface].mainVC setMessage:self.viewModel.datas.count > 0 ? count : nil atIndex:2];
    CGFloat yy = (self.viewModel.datas.count > 0 ? (self.view.height - [self bottomShelterHeight] - self.confirmV.height) : (self.view.height));
    self.confirmV.y = yy;
//    self.baseTable.height = yy;
    self.baseTable.contentInset = UIEdgeInsetsMake([self topShelterHeight], 0, [self bottomShelterHeight] + self.confirmV.height, 0);
}
-(void)reloadData
{
    [FTIndicator showProgressWithMessage:nil];
    [self.viewModel requestDatas];
}
-(void)changeChart:(GYCartShopModel *)model section:(NSInteger)section value:(NSString *)value key:(NSString *)key
{
    if (value.integerValue > 0) {
        [self.viewModel requestChange:model num:value];
    }else{
        [FTIndicator showErrorWithMessage:@"数值应大于零！"];
    }
}
#pragma mark - life
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initilization];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
#pragma mark - delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.viewModel.datas.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellID = @"CellID";
    GYCartGoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:CellID];
    if (cell == nil) {
        cell = [[GYCartGoodsCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    @WeakSelf
    [cell setCallback:^(GYCartShopModel *model, NSString *value, NSString *key) {
        [selfp changeChart:model section:indexPath.section value:value key:key];
    }];
    GYCartShopModel *chart = self.viewModel.datas[indexPath.row];
    cell.model = chart;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = [GYCartGoodsCell finalHeight];
    return height;
}

//- (nullable NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return @"删除";
//}
//-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    if (UITableViewCellEditingStyleDelete == editingStyle) {
//        //删除
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"确定删除吗？" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"删除", nil];
//        //        @WeakSelf
//        [alert showAlertViewWithCompleteBlock:^(NSInteger buttonIndex) {
//            if (1 == buttonIndex) {
//                GYCartShopModel *chart = self.viewModel.datas[indexPath.row];
//                [self.viewModel requestChange:chart num:@"0"];
//            }
//        }];
//    }
//}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    GYCartShopModel *chart = self.viewModel.datas[indexPath.row];
    [self.viewModel chooseCart:chart];
}
@end


/*
 11111111111111111111111111111111111111001111111111111111111111111
 11111111111111111111111111111111111100011111111111111111111111111
 11111111111111111111111111111111100001111111111111111111111111111
 11111111111111111111111111111110000111111111111111111111111111111
 11111111111111111111111111111000000111111111111111111111111111111
 11111111111111111111111111100000011110001100000000000000011111111
 11111111111111111100000000000000000000000000000000011111111111111
 11111111111111110111000000000000000000000000000011111111111111111
 11111111111111111111111000000000000000000000000000000000111111111
 11111111111111111110000000000000000000000000000000111111111111111
 11111111111111111100011100000000000000000000000000000111111111111
 11111111111111100000110000000000011000000000000000000011111111111
 11111111111111000000000000000100111100000000000001100000111111111
 11111111110000000000000000001110111110000000000000111000011111111
 11111111000000000000000000011111111100000000000000011110001111111
 11111110000000011111111111111111111100000000000000001111100111111
 11111111000001111111111111111111110000000000000000001111111111111
 11111111110111111111111111111100000000000000000000000111111111111
 11111111111111110000000000000000000000000000000000000111111111111
 11111111111111111100000000000000000000000000001100000111111111111
 11111111111111000000000000000000000000000000111100000111111111111
 11111111111000000000000000000000000000000001111110000111111111111
 11111111100000000000000000000000000000001111111110000111111111111
 11111110000000000000000000000000000000111111111110000111111111111
 11111100000000000000000001110000001111111111111110001111111111111
 11111000000000000000011111111111111111111111111110011111111111111
 11110000000000000001111111111111111100111111111111111111111111111
 11100000000000000011111111111111111111100001111111111111111111111
 11100000000001000111111111111111111111111000001111111111111111111
 11000000000001100111111111111111111111111110000000111111111111111
 11000000000000111011111111111100011111000011100000001111111111111
 11000000000000011111111111111111000111110000000000000011111111111
 11000000000000000011111111111111000000000000000000000000111111111
 11001000000000000000001111111110000000000000000000000000001111111
 11100110000000000001111111110000000000000000111000000000000111111
 11110110000000000000000000000000000000000111111111110000000011111
 11111110000000000000000000000000000000001111111111111100000001111
 11111110000010000000000000000001100000000111011111111110000001111
 11111111000111110000000000000111110000000000111111111110110000111
 11111110001111111100010000000001111100000111111111111111110000111
 11111110001111111111111110000000111111100000000111111111111000111
 11111111001111111111111111111000000111111111111111111111111100011
 11111111101111111111111111111110000111111111111111111111111001111
 11111111111111111111111111111110001111111111111111111111100111111
 11111111111111111111111111111111001111111111111111111111001111111
 11111111111111111111111111111111100111111111111111111111111111111
 11111111111111111111111111111111110111111111111111111111111111111
 
 
 */

